package com.tbb.app.common.entity;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tbb.app.common.service.CurrentLoginUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author LiuSenLin
 * @date 2020/2/26 11:15
 */
@Slf4j
@Component
public class UpdateAndCreateIdMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private CurrentLoginUserService currentLoginUserService;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (currentLoginUserService != null) {
            String id = currentLoginUserService.getUserId(false);
            if (StringUtils.hasText(id)) {
                this.setFieldValByName("createId", id, metaObject);
                this.setFieldValByName("updateId", id, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (currentLoginUserService != null) {
            String id = currentLoginUserService.getUserId(false);
            if (StringUtils.hasText(id)) {
                this.setFieldValByName("updateId", id, metaObject);
            }
        }
    }
}
